import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt, StrategyOptionsWithRequest } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { UserService } from '../user/user.service';

@Injectable()
export class AuthStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly config: ConfigService,
    private readonly userService: UserService,
  ) {
    super({
      secretOrKey: config.get('jwt.secretkey'),
      ignoreExpiration: false,
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    } as StrategyOptionsWithRequest);
  }
  async validate(payload: { uuid: string; userId: number }) {
    const user = await this.userService.getUserInfo(payload.userId);
    if (!user) {
      throw new UnauthorizedException('用户不存在');
    }
    return user;
  }
}
